import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Typography } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, IdcardOutlined } from '@ant-design/icons';
import { authService } from '../services/authService';
import { useNavigate } from 'react-router-dom';

const { Title } = Typography;

const Register = () => {
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();

    const onFinish = async (values) => {
        setLoading(true);
        try {
            //console.log('提交的表单数据:', values);

            const response = await authService.register(values);
            //console.log('注册响应:', response);

            // 修复：检查响应状态而不是 success 字段
            if (response.status === 200 && response.data) {
                message.success('注册成功，请登录');
                navigate('/login');
            } else {
                message.error('注册失败，请重试');
            }
        } catch (error) {
            console.error('注册错误详情:', error);

            // 改进错误处理
            let errorMessage = '注册失败，请重试';

            if (error.response) {
                // 服务器响应了错误状态码
                const { status, data } = error.response;
                console.log('错误状态码:', status);
                console.log('错误数据:', data);

                if (status === 404) {
                    errorMessage = '服务暂时不可用，请稍后重试';
                } else if (typeof data === 'string') {
                    errorMessage = data;
                } else if (data && data.message) {
                    errorMessage = data.message;
                } else if (data && typeof data === 'object') {
                    // 处理验证错误
                    const errors = Object.values(data).join(', ');
                    errorMessage = errors || errorMessage;
                }
            } else if (error.request) {
                // 请求已发出但没有收到响应
                errorMessage = '网络连接失败，请检查网络';
            }

            message.error(errorMessage);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            minHeight: '100vh',
            background: '#f0f2f5'
        }}>
            <Card style={{ width: 400 }}>
                <div style={{ textAlign: 'center', marginBottom: 24 }}>
                    <Title level={2}>用户注册</Title>
                    <p>创建您的账户</p>
                </div>

                <Form onFinish={onFinish} autoComplete="off">
                    <Form.Item
                        name="username"
                        rules={[
                            { required: true, message: '请输入用户名' },
                            { min: 3, message: '用户名至少3个字符' }
                        ]}
                    >
                        <Input
                            prefix={<UserOutlined />}
                            placeholder="用户名"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item
                        name="email"
                        rules={[
                            { required: true, message: '请输入邮箱' },
                            { type: 'email', message: '请输入有效的邮箱地址' }
                        ]}
                    >
                        <Input
                            prefix={<MailOutlined />}
                            placeholder="邮箱"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item
                        name="fullName"
                        rules={[{ required: true, message: '请输入姓名' }]}
                    >
                        <Input
                            prefix={<IdcardOutlined />}
                            placeholder="姓名"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item
                        name="password"
                        rules={[
                            { required: true, message: '请输入密码' },
                            { min: 6, message: '密码至少6个字符' }
                        ]}
                    >
                        <Input.Password
                            prefix={<LockOutlined />}
                            placeholder="密码"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item
                        name="confirmPassword"
                        dependencies={['password']}
                        rules={[
                            { required: true, message: '请确认密码' },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('password') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('两次输入的密码不一致'));
                                },
                            }),
                        ]}
                    >
                        <Input.Password
                            prefix={<LockOutlined />}
                            placeholder="确认密码"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item>
                        <Button
                            type="primary"
                            htmlType="submit"
                            loading={loading}
                            size="large"
                            style={{ width: '100%' }}
                        >
                            注册
                        </Button>
                    </Form.Item>

                    <div style={{ textAlign: 'center' }}>
                        <Button
                            type="link"
                            onClick={() => navigate('/login')}
                        >
                            已有账号？立即登录
                        </Button>
                    </div>
                </Form>
            </Card>
        </div>
    );
};

export default Register;
